import { canvasToBlob } from '@/utils/common'
import imageLoadManager from './imageLoadManager'

/**
 * 图片滤镜
 * @param frameInfo
 * @param width
 * @param height
 * @returns
 */
export async function imageFilter(
  frameInfo: FrameInfo[],
  width: number,
  height: number,
  filter: (ctx: CanvasRenderingContext2D, index: number) => void
): Promise<FrameInfo[]> {
  const list: FrameInfo[] = []

  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext('2d')

  if (!ctx) {
    throw new Error('Failed to get 2d context')
  }

  const imageList = await imageLoadManager.loadImageList(frameInfo)
  for (let i = 0; i < imageList.length; i++) {
    const image = imageList[i]
    const imageW = image.naturalWidth
    const imageH = image.naturalHeight
    ctx.clearRect(0, 0, width, height)
    ctx.drawImage(image, 0, 0, imageW, imageH, 0, 0, width, height)
    filter(ctx, i)
    const blob = await canvasToBlob(canvas)
    const file = new File([blob], frameInfo[i].name, { type: blob.type })
    list.push({
      name: file.name,
      file,
      url: URL.createObjectURL(file),
    })
  }
  return list
}
